﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RoadFlow.Utility;
using Newtonsoft.Json.Linq;
using System.Data;
using System.IO;

namespace RoadFlow.Mvc.Areas.RoadFlowCoreApi.Controllers
{
    [Route("RoadFlowCoreApi/[controller]")]
    [ApiController]
    public class FlowTaskController : ControllerBase
    {
        /// <summary>
        /// 执行流程
        /// </summary>
        /// <returns></returns>
        [HttpPost("ExecuteTask")]
        [ApiValidate]
        public string ExecuteTask()
        {
            var reader = new StreamReader(Request.Body);
            string json = reader.ReadToEnd();
            JObject jObject_params = null;
            try
            {
                jObject_params = JObject.Parse(json);
            }
            catch { }
           
            string flowId = jObject_params.Value<string>("flowid");//流程ID
            string type = jObject_params.Value<string>("type");//处理类型(freesubmit,submit,save,back,completed,redirect,addwrite,copyforcompleted,taskend)
            string comment = jObject_params.Value<string>("comment");//处理意见
            string taskId = jObject_params.Value<string>("taskid");//当前任务ID
            string instanceId = jObject_params.Value<string>("instanceid");//实例业务ID
            string senderId = jObject_params.Value<string>("senderid");//发送人
            string taskTitle = jObject_params.Value<string>("tasktitle");//任务标题
            JArray steps = null;
            try
            {
                steps = jObject_params.Value<JArray>("steps");//接收步骤及人员
            }
            catch { }
            if (!flowId.IsGuid(out Guid flowGuid))
            {
                return ApiTools.GetErrorJson("参数flowid不是Guid");
            }
            if (!senderId.IsGuid(out Guid senderGuid))
            {
                return ApiTools.GetErrorJson("参数senderid不是Guid");
            }
            Business.User user = new Business.User();
            Business.Organize organize = new Business.Organize();
            var sender = user.Get(senderGuid);
            if (null == sender)
            {
                return ApiTools.GetErrorJson("未找到发送人");
            }
            Business.FlowTask flowTask = new Business.FlowTask();
            Model.FlowTask currentTask = null;
            if (taskId.IsGuid(out Guid taskGuid))
            {
                currentTask = flowTask.Get(taskGuid);
            }
            
            Model.FlowRunModel.Execute executeModel = new Model.FlowRunModel.Execute();
            executeModel.Comment = comment;
            executeModel.ExecuteType = flowTask.GetExecuteType(type);
            executeModel.FlowId = flowGuid;
            executeModel.InstanceId = instanceId;
            executeModel.Sender = sender;
            executeModel.Title = taskTitle;
            if (null != currentTask)
            {
                executeModel.GroupId = currentTask.GroupId;
                executeModel.StepId = currentTask.StepId;
                executeModel.TaskId = currentTask.Id;
                if (instanceId.IsNullOrWhiteSpace())
                {
                    instanceId = currentTask.InstanceId;
                }
                if (taskTitle.IsNullOrWhiteSpace())
                {
                    taskTitle = currentTask.Title;
                }
            }
            else
            {
                var flowRunModel = new Business.Flow().GetFlowRunModel(flowGuid);
                if (null == flowRunModel)
                {
                    return ApiTools.GetErrorJson("未找到流程运行时");
                }
                executeModel.StepId = flowRunModel.FirstStepId;
            }
            if (null != steps)
            {
                List<(Guid, List<Model.User>, DateTime?)> nextSteps = new List<(Guid, List<Model.User>, DateTime?)>();
                foreach (JObject step in steps)
                {
                    Guid stepId = step.Value<string>("id").ToGuid();
                    List<Model.User> users = organize.GetAllUsers(step.Value<string>("users"));
                    string datetTime = step.Value<string>("completedtime");
                    nextSteps.Add((stepId, users, datetTime.IsDateTime(out DateTime dateTime) ? dateTime : new DateTime?()));
                }
                executeModel.Steps = nextSteps;
            }
            Model.FlowRunModel.ExecuteResult executeResult = flowTask.Execute(executeModel);
            int errCode = executeResult.IsSuccess ? 0 : 2001;
            string errMsg = executeResult.Messages;
            JObject jObject1 = ApiTools.GetJObject(errCode, errMsg);
            jObject1.Add("data", JObject.FromObject(executeResult));
            return jObject1.ToString(Newtonsoft.Json.Formatting.None);
        }

        /// <summary>
        /// 查询待办事项 
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetWaitTasks")]
        [ApiValidate]
        public string GetWaitTasks()
        {
            var reader = new StreamReader(Request.Body);
            string json = reader.ReadToEnd();
            JObject jObject_params = null;
            try
            {
                jObject_params = JObject.Parse(json);
            }
            catch { }
            
            string userId = jObject_params.Value<string>("userid");
            int pageSize = jObject_params.Value<string>("pagesize").ToInt(10);
            int pageNumber = jObject_params.Value<string>("pagenumber").ToInt(1);
            string flowId = jObject_params.Value<string>("flowid");
            string title = jObject_params.Value<string>("title");
            string startDate = jObject_params.Value<string>("startdate");
            string endDate = jObject_params.Value<string>("enddate");
            string order = jObject_params.Value<string>("order");
            if (!userId.IsGuid(out Guid userGuid))
            {
                return ApiTools.GetErrorJson("用户id错误");
            }
            if (flowId.IsNullOrWhiteSpace())
            {
                return ApiTools.GetErrorJson("流程ID不能为空");
            }
            DataTable tasks = new Business.FlowTask().GetWaitTask(pageSize, pageNumber, userGuid, flowId, title, startDate, endDate, order.IsNullOrWhiteSpace() ? "ReceiveTime DESC" : order, out int count);
            JArray jArray = new JArray();
            JObject jObject = ApiTools.GetJObject();
            foreach (DataRow dr in tasks.Rows)
            {
                JObject jObject1 = new JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "title", dr["Title"].ToString() },
                    { "flowid", dr["FlowId"].ToString() },
                    { "flowname", dr["FlowName"].ToString() },
                    { "stepid", dr["StepId"].ToString() },
                    { "instanceid", dr["InstanceId"].ToString() },
                    { "groupid", dr["GroupId"].ToString() },
                    { "stepname", dr["StepName"].ToString() },
                    { "senderid", dr["SenderId"].ToString() },
                    { "sendername", dr["SenderName"].ToString() },
                    { "receivetime", dr["ReceiveTime"].ToString().ToDateTime().ToShortDateTimeString() },
                    { "completedtime", dr["CompletedTime"].ToString().IsDateTime(out DateTime ctime) ? ctime.ToShortDateTimeString() : "" },
                    { "status", dr["status"].ToString().ToInt() },
                    { "note", dr["Note"].ToString() }
                };
                jArray.Add(jObject1);
            }
            jObject.Add("count", count);
            jObject.Add("data", jArray);
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }

        /// <summary>
        /// 查询已办事项
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetCompletedTasks")]
        [ApiValidate]
        public string GetCompletedTasks()
        {
            var reader = new StreamReader(Request.Body);
            string json = reader.ReadToEnd();
            JObject jObject_params = null;
            try
            {
                jObject_params = JObject.Parse(json);
            }
            catch { }
            
            string userId = jObject_params.Value<string>("userid");
            int pageSize = jObject_params.Value<string>("pagesize").ToInt(10);
            int pageNumber = jObject_params.Value<string>("pagenumber").ToInt(1);
            string flowId = jObject_params.Value<string>("flowid");
            string title = jObject_params.Value<string>("title");
            string startDate = jObject_params.Value<string>("startdate");
            string endDate = jObject_params.Value<string>("enddate");
            string order = jObject_params.Value<string>("order");
            if (!userId.IsGuid(out Guid userGuid))
            {
                return ApiTools.GetErrorJson("用户id错误");
            }
            if (flowId.IsNullOrWhiteSpace())
            {
                return ApiTools.GetErrorJson("流程ID不能为空");
            }
            DataTable tasks = new Business.FlowTask().GetCompletedTask(pageSize, pageNumber, userGuid, flowId, title, startDate, endDate, order.IsNullOrWhiteSpace() ? "CompletedTime1 DESC" : order, out int count);
            JArray jArray = new JArray();
            JObject jObject = ApiTools.GetJObject();
            foreach (DataRow dr in tasks.Rows)
            {
                JObject jObject1 = new JObject
                {
                    { "id", dr["Id"].ToString() },
                    { "title", dr["Title"].ToString() },
                    { "flowid", dr["FlowId"].ToString() },
                    { "flowname", dr["FlowName"].ToString() },
                    { "stepid", dr["StepId"].ToString() },
                    { "instanceid", dr["InstanceId"].ToString() },
                    { "groupid", dr["GroupId"].ToString() },
                    { "stepname", dr["StepName"].ToString() },
                    { "senderid", dr["SenderId"].ToString() },
                    { "sendername", dr["SenderName"].ToString() },
                    { "receivetime", dr["ReceiveTime"].ToString().ToDateTime().ToShortDateTimeString() },
                    { "completedtime", dr["CompletedTime"].ToString().IsDateTime(out DateTime ctime) ? ctime.ToShortDateTimeString() : "" },
                    { "completedtime1", dr["CompletedTime1"].ToString().IsDateTime(out DateTime ctime1) ? ctime1.ToShortDateTimeString() : "" },
                    { "status", dr["status"].ToString().ToInt() },
                    { "note", dr["Note"].ToString() }
                };
                jArray.Add(jObject1);
            }
            jObject.Add("count", count);
            jObject.Add("data", jArray);
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }

        /// <summary>
        /// 查询一个实例组列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetGroupTasks")]
        [ApiValidate]
        public string GetGroupTasks()
        {
            var reader = new StreamReader(Request.Body);
            string json = reader.ReadToEnd();
            JObject jObject_params = null;
            try
            {
                jObject_params = JObject.Parse(json);
            }
            catch { }
            
            string groupId = jObject_params.Value<string>("groupid");
            if (!groupId.IsGuid(out Guid groupGuid))
            {
                return ApiTools.GetErrorJson("参数groupid不是有效的Guid字符串");
            }
            var tasks = new Business.FlowTask().GetListByGroupId(groupGuid);
            JObject jObject = ApiTools.GetJObject();
            jObject.Add("data", JArray.FromObject(tasks));
            return jObject.ToString(Newtonsoft.Json.Formatting.None);
        }
    }
}